package auth

import (
	"context"
	"encoding/json"
	"gysa-share01/common"
	"net/http"
)

type registerByPwdRequest struct {
	UserName string `json:"username"`
	Password string `json:"password"`
	Nickname string `json:"nickname"`
}

type loginRequest struct {
	UserName string `json:"username"`
	Password string `json:"password"`
}

type registerByPwdResponse struct {
	common.Response
	Token string `json:"token"`
}

func DecodeLoginRequest(_ context.Context, r *http.Request) (interface{}, error) {
	var request loginRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		return nil, err
	}
	return request, nil
}

func DecodeRegisterByPwdRequest(_ context.Context, r *http.Request) (interface{}, error) {
	var request registerByPwdRequest
	if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
		return nil, err
	}
	return request, nil
}

func EncodeResponse(c context.Context, w http.ResponseWriter, response interface{}) error {
	w.Header().Set("Content-Type", "application/json;charset=utf-8")
	comRes, ok := response.(common.Response)
	if ok && comRes.ErrorCode > 0 {
		w.WriteHeader(400)
	} else {
		w.WriteHeader(200)
	}
	return json.NewEncoder(w).Encode(response)
}
